<?php

/**
 * nmp版 - 新后台个人中心数据看板
 * Class DashBoardAction
 * @author lilei<LL_strive@163.com> 2017-06-23
 */
class DashBoardAction extends Action {

    /**
     * 类初始化函数
     */
    public function _initialize()
    {

    }

    /**
     * 获得数据看板列表
     */
    public function getDashBoardList($cid, $userId)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $dashboard_db      = M('dashboard');
        $dashboard_user_db = M('dashboard_user');
        Session::switchCustomer($customerId);

        /** 3. 筛选条件 */
        $dashboard_where = [
            'deleted'   => 0
        ];
        $dashboard_user_where = [
            'cid'       => $cid,
            'userId'    => $userId,
            'status'    => 1    // 0-关闭/1-开启
        ];

        /** 4. 查询看板数据 */
        // 4.1 查询用户看板数据
        $userDashboard_boardIds = $dashboard_user_db
            ->where($dashboard_user_where)
            ->order('sort asc')
            ->getField('boardId', TRUE);
        $data = $dashboard_db->where($dashboard_where)->select();
        foreach ($data as $k => $v) {
            $data[$k]['isSelect'] = (in_array($v['id'], $userDashboard_boardIds)) ? 1 : 0;
        }

        /** 5. 数据返回 */
        if ($data) {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '数据看板获取成功',
                'data'  => $data
            ]);
        } else {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '暂无看板数据',
                'data'  => []
            ]);
        }

    }

    /**
     * 获取某个登录用户已配置的数据看板
     *
     * @param int $cid      这个用户的cid
     * @param int $userId   这个用户自身的userId
     */
    public function getUserDashBoardlList($cid, $userId)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $dashboard_db      = M('dashboard');
        $dashboard_user_db = M('dashboard_user');
        Session::switchCustomer($customerId);

        /** 3. 用户看板筛选条件 */
        $dashboard_user_where = [
            'cid'       => $cid,
            'userId'    => $userId,
            'status'    => 1    // 0-关闭/1-开启
        ];

        /** 4. 查询用户看板数据 */
        $userDashboard_boardIds = $dashboard_user_db
            ->where($dashboard_user_where)
            ->order('sort asc')
            ->getField('boardId', TRUE);

        /** 5. 根据看板id, 查询组合看板信息 */
        // 使用in, 避免多表关联和for循环多次查询. !使用in虽然避免的循环多次查询, 但是, 排序就实现不了了
//        $dashboard_where['id'] = array('in', $userDashboard_boardIds);
//        $dashboards = $dashboard_db->where($dashboard_where)->select();

        $dashboards = [];
        foreach ($userDashboard_boardIds as $boardId_index => $boardId) {
            $dashboard_where = ['id' => $boardId];

            $dashboard = $dashboard_db->where($dashboard_where)->select();
            array_push($dashboards, $dashboard[0]);
        }

        /** 6. 数据返回 */
        if ($dashboards) {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '用户看板信息获取成功',
                'data'  => $dashboards
            ]);
        } else {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '该用户暂无看板数据',
                'data'  => []
            ]);
        }
    }

    /**
     * 用户订阅数据看板(批量)
     *
     * @param int   $cid          这个用户的cid
     * @param int   $userId       这个用户自身的userId
     * @param array $dashBoardId  用户订阅的数据看板的id
     */
    public function subscribeDashBoard($cid, $userId, $dashBoardId)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $dashboard_user_db = M('dashboard_user');
        Session::switchCustomer($customerId);

        /** 3. 组织数据插入 */
        /** 3.1 查询这个用户已有看板的最大排序号 */
        $sort =  $dashboard_user_db->where(['cid' => $cid, 'userId' => $userId])->order('sort desc')->getField('sort');
        $sort_max = ($sort) ? $sort : 0;    // 默认从1开始

        $where = [
            'cid'       => $cid,
            'userId'    => $userId,
        ];
        $flag = 0;  // 标记是否所有看板注册成功: 0-所有成功/1-有部分错误
        $dashBoardId = json_decode($dashBoardId);
        foreach ($dashBoardId as $index => $boardId) {
            $sort_max++;    // 默认排序追加

            $where['boardId'] = $boardId;
            // 如果能查出id, 则说明之前开启过
            $user_board_id = $dashboard_user_db->where($where)->getField('id');
            if ($user_board_id) {   // 如果这个用户的这个board, 则修改状态和排序即可
                $data['status'] = 1;
                $data['sort']   = $sort_max;    // 由于是再次打开, 所以排序会修改. 这会导致中间会有空余排序 / 不修改则占据之前已有排序位置
                // 如果修改无变化的话, 也是0
                $result_id = $dashboard_user_db->where(['id' => $user_board_id])->save($data);
            } else {    // 否则新增
                $data = [
                    'cid'       => $cid,
                    'userId'    => $userId,
                    'boardId'   => $boardId,
                    'status'    => 1,
                    'sort'      => $sort_max
                ];
                $result_id = $dashboard_user_db->add($data);
            }

            // 注意修改无变化的情况, 此时值也是0
            if ($result_id === false) {  // 插入数据表有错误
                $flag = 1;  // 如果有部分数据错误, 修改标记
                \Log::write('用户注册看板时部分数据插入有错误_DashBoardAction::subscribeDashBoard_' . json_encode($data));
            }
        }

        /** 4. 返回数据 */
        if ($flag) {    // 有部分错误
            Output::instance()->object([
                'code'  => 1,
                'msg'   => '看板数据注册存在错误'
            ]);
        } else {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '看板数据注册成功'
            ]);
        }
    }

    /**
     * 用户取消订阅数据看板(批量)
     *
     * @param int   $cid          这个用户的cid
     * @param int   $userId       这个用户自身的userId
     * @param array $dashBoardId  用户订阅的数据看板的id
     */
    public function unSubscribeDashBoard($cid, $userId, $dashBoardId)
    {
        /** 1. 判断是否登录 */
        $this->retVal = Session::init();
        if (!$this->retVal) {
            Output::instance()->resultCode(code_access_denied);
            exit;
        }

        /** 2. 数据表模型 */
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $dashboard_user_db = M('dashboard_user');
        Session::switchCustomer($customerId);

        /** 3. 组织数据修改 */
        $where = [
            'cid'       => $cid,
            'userId'    => $userId,
        ];
        $flag = 0;  // 标记是否所有看板取消成功: 0-所有成功/1-有部分错误
        $dashBoardId = json_decode($dashBoardId);
        foreach ($dashBoardId as $index => $boardId) {
            $where['boardId'] = $boardId;

            $data['status'] = 0;
            $result = $dashboard_user_db->where($where)->save($data);

            if ($result !== 0 || $result !== 1) {   // 部分修改有错误
                $flag = 1;
                \Log::write('用户取消看板时部分数据修改有错误_DashBoardAction::unSubscribeDashBoard_' . json_encode($where));
            }
        }

        /** 4. 返回数据 */
        if ($flag) {    // 有部分错误
            Output::instance()->object([
                'code'  => 1,
                'msg'   => '看板数据取消存在错误'
            ]);
        } else {
            Output::instance()->object([
                'code'  => 0,
                'msg'   => '看板数据取消成功'
            ]);
        }
    }

}